import { getItem } from '@hs-admin/utils'
import { Layout, Menu, MenuProps } from 'antd'
import React, { useEffect, useState } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'

const { Content, Sider } = Layout

const Setting: React.FC = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const permissons = getItem('PERMISSIONS_OPERATE') || []
  const menuItems: { label: string; key: string; routerlist?: string[] }[] = []
  if (permissons.includes('sg.hs_database.manage')) {
    menuItems.push({
      label: '数据库查询配置',
      key: '/setting/dataItem',
      routerlist: ['/setting/dataItemDetail']
    })
  }
  if (permissons.includes('sg.industry_map.manage')) {
    menuItems.push({ label: '产业链查询配置', key: '/setting/atlas', routerlist: ['/setting/atlasDetail', '/setting/dataItemDetail'] })
  }
  menuItems.push({ label: '企业榜单维护', key: '/setting/companyRank' })
  menuItems.push({ label: '创新资质维护', key: '/setting/companyQualifications' })

  const [current, setCurrent] = useState('/setting/dataItem')

  const onClick: MenuProps['onClick'] = (e) => {
    setCurrent(e.key)
    navigate(e.key)
  }

  useEffect(() => {
    menuItems?.forEach((first: any) => {
      if (first.key === location.pathname || first.routerlist?.includes(location.pathname)) {
        setCurrent(first.key)
      }
    })
    if (location.pathname === '/setting') {
      if (menuItems.length) {
        navigate(menuItems[0].key)
      } else {
        navigate('/404')
      }
    }
  }, [location])

  return (
    <Layout>
      <Sider breakpoint="lg" collapsedWidth="0" theme="light" className="overflow-auto">
        <Menu selectedKeys={[current]} items={menuItems} onClick={onClick} />
      </Sider>
      <Layout className="overflow-auto">
        <Content>
          <div
            style={{
              padding: 16,
              height: '100%'
            }}>
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  )
}

export default Setting
